<template>
  <div class="batch-edit-picture-modal">
    <a-modal v-model:open="visible" title="批量编辑图片" :footer="false" @cancel="closeModal">
      <a-typography-paragraph type="secondary">只对当前页面展示的图片生效</a-typography-paragraph>
      <!-- 批量编辑图片表单 -->
      <a-form layout="vertical" :model="formData" @finish="handleSubmit">
        <a-form-item label="图片分类" name="category">
          <a-auto-complete
            v-model:value="formData.category"
            placeholder="可自定义图片分类"
            :options="categoryOptions"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="图片标签" name="tags">
          <a-select
            v-model:value="formData.tags"
            mode="tags"
            placeholder="可自定义图片标签"
            :options="tagOptions"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="命名规则" name="nameRule">
          <a-input
            v-model:value="formData.nameRule"
            placeholder="输入命名规则，输入“{序号}”会自动生成序号"
            allow-clear
            style="max-width: 500px"
          />
        </a-form-item>
        <a-typography-paragraph>示例：</a-typography-paragraph>
        <a-typography-paragraph type="secondary"
          >命名规则{序号} 批量编辑后：命名规则1、命名规则2、命名规则3...以此类推
        </a-typography-paragraph>
        <div style="margin-bottom: 16px" />
        <a-form-item>
          <a-flex>
            <a-button type="text" danger @click="cancelEditByBatch" block :icon="h(CloseOutlined)">
              取消
            </a-button>
            <a-button type="primary" html-type="submit" block :icon="h(EditOutlined)">
              提交批量编辑
            </a-button>
          </a-flex>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import { h, onMounted, reactive, ref, watch } from 'vue'
import {
  editPictureByBatchUsingPost,
  listPictureTagCategoryUsingGet,
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import { CloseOutlined, EditOutlined } from '@ant-design/icons-vue'

interface Props {
  pictureList: API.PictureVO[]
  spaceId: number
  onSuccess: () => void
}

const props = withDefaults(defineProps<Props>(), {})

// 分享弹窗是否可见
const visible = ref<boolean>(false)

/**
 * 打开弹窗
 */
const openModal = () => {
  visible.value = true
}
/**
 * 关闭弹窗
 * @param e
 */
const closeModal = (e: MouseEvent) => {
  visible.value = false
}

// 图片信息表单，类型是编辑图片请求体，默认是空对象
const formData = reactive<API.PictureEditByBatchRequest>({
  category: '',
  tags: [],
  nameRule: '',
})

/**
 * 提交表单批量编辑图片信息
 * @param values
 */
const handleSubmit = async (values: any) => {
  if (!props.pictureList) {
    message.error('操作失败，图片列表解析错误')
  }
  const res = await editPictureByBatchUsingPost({
    pictureIdList: props.pictureList.map((picture) => picture.id),
    spaceId: props.spaceId,
    ...values,
  })
  if (res.data.code === 0 && res.data.data) {
    message.success('批量编辑成功')
    // 关闭弹窗
    // @ts-ignore
    closeModal()
    // 通知父组件刷新数据
    // @ts-ignore
    props.onSuccess()?.()
  } else {
    message.error('批量编辑失败，' + res.data.message)
  }
}

/**
 * 取消批量编辑图片
 */
const cancelEditByBatch = () => {
  message.success('取消批量编辑图片成功')
  // '取消批量编辑图片后，关闭弹窗
  visible.value = false
}

// 清空批量编辑表单数据
const clearForm = () => {
  formData.category = ''
  formData.tags = []
  formData.nameRule = ''
  formData.pictureIdList = []
}

/**
 * 暴露函数给父组件
 */
defineExpose({
  openModal,
  clearForm,
})

const categoryOptions = ref<String[]>([])
const tagOptions = ref<String[]>()

/**
 * 进入创建图片页面 展示默认标签和分类选项
 */
const getTagCategoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.data.code === 0 && res.data.data) {
    // @ts-ignore
    tagOptions.value = (res.data.data.tagList ?? []).map((data: String) => {
      return {
        value: data,
        label: data,
      }
    })
    // @ts-ignore
    categoryOptions.value = (res.data.data.categoryList ?? []).map((data: String) => {
      return {
        value: data,
        label: data,
      }
    })
  } else {
    message.error('默认分类标签列表展示失败，' + res.data.message)
  }
}

onMounted(() => {
  getTagCategoryOptions()
})

// 监听图片标签数量，超过6个标签给出警告
watch(
  () => formData.tags,
  (newTags) => {
    if (newTags && newTags.length > 6) {
      message.warn('标签数量至多 6 个，请适当减少')
    }
  },
  { deep: true },
)
</script>
